/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufjf.pos.controller;

import br.ufjf.pos.model.Nivel;
import br.ufjf.pos.model.Usuario;
import br.ufjf.pos.model.dao.NivelDAO;
import br.ufjf.pos.model.dao.UsuarioDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author cleber
 */
public class LogarController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, ClassNotFoundException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String login = request.getParameter("username");
        String senha = request.getParameter("senha");
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");        
        Boolean dadosValidos = true;
        
        /* Valida Campos Obrigatorios */
        if(login == null || login.equals("") ){            
            rd = request.getRequestDispatcher("erro.jsp");        
            //request.setAttribute("pag", "erro.jsp");
            request.setAttribute("msg", "Favor preencher campo de usuário.");
            dadosValidos = false;
        }
        if(senha == null || senha.equals("") ){            
            rd = request.getRequestDispatcher("erro.jsp");        
            //request.setAttribute("pag", "erro.jsp");
            request.setAttribute("msg", "Favor preencher campo de senha.");
            dadosValidos = false;
        }        
        
        if(dadosValidos){
            try{
                //Codigo para criar um usuario no banco. Para testes
                //Usuario novoUsuario = new Usuario("adm","123",1,1);
                //new UsuarioDAO().inserir(novoUsuario);

                Usuario u = new UsuarioDAO().validaLogin(login, senha);
                
                if (u==null){
                    rd = request.getRequestDispatcher("erro.jsp"); 
                    request.setAttribute("msg", "Senha ou Login incorreto.");
                }else{
                    //NivelDAO objNivelDao = new NivelDAO();
                    
                    HttpSession sessao = request.getSession();
                    sessao.setAttribute("Logado", true);
                    sessao.setAttribute("usuario", u);
                    
                    //Necessario para salvar agendamento de atendimento, entre outros.
                    sessao.setAttribute("idUsuario", u.getIdFuncionario()); 
                    
                    
                    sessao.setAttribute("listaNivel", new NivelDAO().buscarTodos());
                    
                    //sessao.setAttribute("usuario", nivel);
                    
                    
                    request.setAttribute("pag", "adm.jsp");                    
                    rd = request.getRequestDispatcher("adm.jsp"); 
                    
                }                
            } catch (SQLException ex) {
                request.setAttribute("pag", "erro.jsp");
                request.setAttribute("msg", "Erro de conexão" + ex.getMessage());
                
            } catch (ClassNotFoundException ex) {
                request.setAttribute("pag", "erro.jsp");
                request.setAttribute("msg", "Erro de conexão nao encontrada" + ex.getMessage());
            }
        }
        
        
        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LogarController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LogarController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LogarController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LogarController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
